package org.yi.fc.security.shiro;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.yi.fc.entity.FRolePermission;
import org.yi.fc.entity.FSysUser;
import org.yi.fc.entity.FUserRole;

/**
 * FinalCMS的认证实列
 */
public class FinalCMSRealm extends JdbcRealm {

	/**
	 * 授权, 赋予相关权限
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		String username = String.valueOf(principal.iterator().next());
		FSysUser user = FSysUser.dao.getUserByName(username);
		
		if(user != null){
			List<String> roleNames = FUserRole.dao.getRoleNames(user.getLong("id"));
			info.addRoles(roleNames);
			
			List<String> permissions = FRolePermission.dao.getPermissinsByRoleNames(roleNames);
			info.addStringPermissions(permissions);
			
		}
		
		return info;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		UsernamePasswordToken upt = (UsernamePasswordToken) token ;
		
		String username = String.valueOf(upt.getUsername()).trim();
		String password = String.valueOf(upt.getPassword());
		
		boolean userExist = FSysUser.dao.userExist(username);  
		
		if(userExist){
			FSysUser user = FSysUser.dao.uniqueResult(username, password);
			if(user == null){
				throw new CredentialsException("密码不正确");
			}else{
				SecurityUtils.getSubject().getSession().setAttribute("f_sys_user", user);
				return new SimpleAuthenticationInfo(username, password,  getName());
			}
		}else{
			throw new AccountException("用户名【" + username + "】不存在");
		}
		
	}

}
